import axios from "axios";
import { Message } from "element-ui";

import router from "@/router";

import { IGNORE_API, SUCCESS_CODE } from "./codeMsg";
// import { log } from "@antv/g2plot/lib/utils";
// import $i18n from "../i18n";

const service = axios.create({
  timeout: 1000 * 60 * 5,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
});

service.interceptors.request.use(
  (config) => {
    // axios的源码在请求类型是get时，当未设置requestData的时候会删掉Content-Type的设置，其这么做的原因在于是Get请求本身是不需要Content-Type
    // if (config.method === "get") {
    //   //  给data赋值以绕过if判断
    //   config.data = true;
    // }
    if (config.params && config.params.multiple) {
      config.headers["Content-Type"] = "multipart/form-data;boundary = " + new Date().getTime();
      delete config.params.multiple;
    }
    // 模拟指定请求令牌
    const token = localStorage.getItem("token") || sessionStorage.getItem("token");
    // 多租户
    const tenantId = localStorage.getItem("tenantId");
    config.headers["Authorization"] = token;

    if (tenantId) config.headers["tenantId"] = tenantId;
    // 多语言
    // config.headers["Accept-Language"] = $i18n.locale
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

service.interceptors.response.use(
  (res) => {
    // 不满足成功code并且不再忽略api列表里
    if (
      !SUCCESS_CODE.includes(res.data.status) &&
      !IGNORE_API.includes(res.config.url) &&
      !(res.data instanceof Blob)
    ) {
      Message({
        type: "error",
        message: res.data.msg,
        duration: 5000,
      });
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (error) => {
    let { message, response } = error;
    if (response.status === 401) {
      // 跳转登录
      if (router.currentRoute.path !== "/login") {
        Message.closeAll();
        setTimeout(() => {
          sessionStorage.removeItem("userInfo");
          sessionStorage.removeItem("token");
          localStorage.removeItem("token");

          const VITE_APP_CLIENT_URl = window.$envConfig("VITE_APP_CLIENT_URl");

          let isSharePath = new RegExp(`^${VITE_APP_CLIENT_URl}/share/dashboard/(.*?)`);
          let redirect = `${VITE_APP_CLIENT_URl}/login`;
          if (isSharePath.test(window.location.href)) {
            redirect += `?redirect=${window.location.href.replace(VITE_APP_CLIENT_URl, "")}`;
          }
          location.href = redirect;
        }, 3000);
      }
    } else {
      Message({
        type: "error",
        message: message === "Network Error" ? "网络错误" : message,
        duration: 5000,
      });
    }
    return Promise.reject(error);
  }
);
export default service;
